package com.project.file.tool;

import cn.hutool.core.util.StrUtil;
import com.project.bean.file.SaveFileOutDTO;
import com.project.core.util.CommonUtil;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Objects;

/**
 * @author mengxj
 */
public class LocalFile extends BaseFile {

    private static LocalFile instance;

    public static BaseFile getInstance(){
        if(Objects.isNull(instance)){
            synchronized (LocalFile.class){
                if(Objects.isNull(instance)){
                    instance = new LocalFile();
                }
            }
        }
        return instance;
    }

    @Override
    public boolean removeFile(String bucket, String objectName) {
        String address = String.format("%s/%s", bucket, objectName);
        File file = new File(address);
        if(file.exists()){
            return file.delete();
        }
        return true;
    }

    @Override
    public SaveFileOutDTO saveFile(String fileName, String bucket, InputStream is, String suffix) throws Exception {
        String objectName = super.getObjectName(suffix, fileName);
        String address = String.format("%s/%s", bucket, objectName);
        String regex = String.format("/%s$", fileName);
        String dir = address.replaceAll(regex, StrUtil.EMPTY);
        File file = new File(dir);
        boolean mkdir = true;
        if(!file.exists()){
            mkdir = file.mkdirs();
        }
        if(!mkdir){
            CommonUtil.throwException(String.format("文件夹 %s 不存在且创建文件夹失败！", dir));
        }
        try (FileOutputStream os = new FileOutputStream(address)){
            byte[] bytes = new byte[1024];
            int d;
            while ((d = is.read(bytes)) != -1){
                os.write(bytes, 0, d);
            }
            os.flush();
        }
        return SaveFileOutDTO.builder().fileName(fileName).suffix(suffix).bucket(bucket).objectName(objectName).url(address).build();
    }

    @Override
    public void download(String bucket, String objectName, String fileName) {
        String address = String.format("%s/%s", bucket, objectName);
        HttpServletResponse response = CommonUtil.getResponse();
        response.setHeader("Content-disposition", "attachment; filename=" + fileName);
        try (InputStream is = new FileInputStream(address);
             OutputStream os = response.getOutputStream()){
            byte[] bytes = new byte[1024];
            int len;
            while ((len = is.read(bytes)) != -1){
                os.write(bytes, 0, len);
            }
        }catch (IOException e){
            String msg = String.format("下载文件失败! 参数：bucket %s objectName %s, 错误信息：==> %s: %s", bucket, objectName, e.getClass(), e.getMessage());
            CommonUtil.throwException(msg, e);
        }
    }
}
